package com.javafm.jwt.helljwt;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class AuthInterceptor implements HandlerInterceptor {

    public void error(HttpServletResponse response) {
        response.setHeader("Content-Type", "text/plain;charset=utf-8");
        try {
            response.getWriter().write("未授权的请求");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String uri = request.getRequestURI();

        // 登录接口 `/login` 不需要校验
        if (uri.indexOf("/login") == 0) {
            return true;
        }

        // 获取header中的token
        String token = request.getHeader("Authorization");
        if (token == null) {
            error(response);
            return false;
        }

        // 从token中提取出username，这个是在登录创建token时放进去的
        String username;
        try {
            username = JWT.decode(token).getAudience().get(0);
        } catch (JWTDecodeException e) {
            error(response);
            return false;
        }
        // 假设这里根据 username 去数据库查询出用户信息，在这里我们写死是password
        String password = "admin"; // 假设这里是根据用户名从数据库查询出来的用户信息

        // 验证token
        // Algorithm.HMAC256 参数放的不一定是密码，这个的看你创建token时，放的是什么内容，这里就传入什么内容
        JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(password)).build();

        try {
            jwtVerifier.verify(token);
            return true;
        }catch (JWTVerificationException e) {
            error(response);
            return false;
        }
    }
}
